import { constantRoutes } from '@/router'
import { transListToTreeData } from '@/utils'
const state = {
  routes: constantRoutes
}
const mutations = {
  // 将静态路由和动态路由合并存储
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}
const actions = {
// 整理服务器返回的权限信息menuList，生成动态路由
  createNewRoutes(context, payload) {
  // conext.commit('setRoutes,'最终的动态路由')
    // console.log(payload, 'payload')

    // function transListToTreeData(list, rootValue) {
    //   const arr = []
    //   list.forEach(item => {
    //     if (item.pid === rootValue) {
    //     // 找到了匹配的节点
    //     // 当前节点的id 和 当前节点的子节点的pid是想等的
    //       const children = transListToTreeData(list, item.id) // 找到的节点的子节点
    //       if (children.length) item.children = children // 将子节点赋值给当前节点
    //       arr.push(item)
    //     }
    //   })
    //   return arr
    // }

    function loadView(comStr) {
      try {
        if (comStr === 'layout') {
        // 加载layout组件
        // import layout from '@/layout/index.vue  ===  require('@/layout/index.vue').default
          return require('@/layout/index.vue').default
        } else {
        // 直接在 comStr传过来的模块
          return require('@/views/' + comStr + '.vue').default
        }
      } catch (error) {
        return require('@/views/error.vue')
      }
    }

    const newRoutes = payload.map(item => {
      return {
        path: item.path,
        name: item.mark,
        meta: {
          title: item.title,
          icon: item.icon
        },
        hidden: item.is_show !== 1,
        redirect: item.redirect,
        component: loadView(item.component),
        pid: item.pid,
        id: item.id
      }
    })
    return transListToTreeData(newRoutes, 0)
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
